import React from 'react';
import { useNavigate } from 'react-router-dom';
import { request } from '@/utils/request';
import { useI18n, toApiLanguageCode } from '@/utils/in18';
import { getStoredBearerToken, hasStoredToken } from '@/utils/auth';

// 页面：我喜欢的作品列表
// 职责：
// 1) 进入页面后请求 "/api/work/getMyLikedWorksRoute" 获取喜欢的作品（滚动懒加载）
// 2) 列表项展示图片、被赞数、作者昵称与头像（明暗主题 + 移动/PC 适配）
// 3) 点击项打开子组件弹窗，查看大图、标签、创建时间，支持“移除喜欢”和“创建图片”
// 4) 确认移除喜欢后调用 "/api/work/toggleWorkLikeRoute" 并从列表移除该项

// 数据结构：与接口返回字段保持一致，便于透传
export type LikedWork = {
  id: number;
  owner_user_id?: number;
  template_id?: number;
  image_url: string;
  role_prompt?: string;
  display_prompt?: string;
  likes_count?: number;
  used_as_template_count?: number;
  created_at?: string;
  nickname?: string;
  avatar_url?: string;
};

// 子组件：弹窗（单独封装在本目录的 components 中）
import LikedWorkModal from './components/LikedWorkModal.tsx';

const PAGE_SIZE = 20; // 每页条数（可根据需要调整）

const MyLikedWorkListPage: React.FC = () => {
  // 分页与数据
  const [list, setList] = React.useState<LikedWork[]>([]);
  const [page, setPage] = React.useState<number>(1);
  const [total, setTotal] = React.useState<number>(0);
  const [loading, setLoading] = React.useState<boolean>(false);
  const [noMore, setNoMore] = React.useState<boolean>(false);

  // 弹窗状态
  const [modalOpen, setModalOpen] = React.useState<boolean>(false);
  const [current, setCurrent] = React.useState<LikedWork | null>(null);

  // 管理/多选状态
  const [editMode, setEditMode] = React.useState<boolean>(false);
  const [selectedIds, setSelectedIds] = React.useState<number[]>([]);
  const [bulkConfirmOpen, setBulkConfirmOpen] = React.useState<boolean>(false);
  const [bulkConfirmLoading, setBulkConfirmLoading] = React.useState<boolean>(false);
  // 卡片层面的二次确认状态（点击点赞区域触发）
  const [confirmOpenCard, setConfirmOpenCard] = React.useState<boolean>(false);
  const [confirmTargetId, setConfirmTargetId] = React.useState<number | null>(null);
  const [confirmLoadingCard, setConfirmLoadingCard] = React.useState<boolean>(false);

  // 语言环境（用于语言码转换）
  const { locale, t } = useI18n();
  const navigate = useNavigate();
  const goBack = React.useCallback(() => {
    try {
      if (window.history.length > 1) {
        navigate(-1);
      } else {
        navigate('/');
      }
    } catch {
      navigate('/');
    }
  }, [navigate]);

  // 视口滚动容器引用（使用布局的内容区滚动，因此监听 window）
  const scrollHandlerRef = React.useRef<() => void>(() => { });

  // 函数：加载一页数据
  const fetchPage = React.useCallback(async (pageToLoad: number, replace = false) => {
    if (loading) return;
    if (!hasStoredToken()) return;
    setLoading(true);
    try {
      const authHeader = getStoredBearerToken();
      if (!authHeader) return;
      const res = await request.post('/api/work/getMyLikedWorksRoute', {
        page: pageToLoad,
        page_size: PAGE_SIZE,
      }, { headers: { Authorization: authHeader } });
      if (res?.data?.success === true) {
        const data: LikedWork[] = Array.isArray(res.data.data) ? res.data.data : [];
        setList((prev) => (replace ? data : prev.concat(data)));
        const returnedTotal = Number(res.data.total || 0);
        const returnedPage = Number(res.data.page || pageToLoad);
        const returnedSize = Number(res.data.page_size || PAGE_SIZE);
        setTotal(returnedTotal);
        setPage(returnedPage);
        // 计算是否没有更多数据
        if (data.length === 0 || (returnedTotal > 0 && returnedPage * returnedSize >= returnedTotal)) {
          setNoMore(true);
        } else {
          setNoMore(false);
        }
      }
    } finally {
      setLoading(false);
    }
  }, [loading]);

  // 初始化：加载第一页
  React.useEffect(() => {
    setList([]);
    setNoMore(false);
    fetchPage(1, true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [locale]);

  // 滚动懒加载：监听页面滚动，接近底部时拉取下一页
  React.useEffect(() => {
    const handleScroll = () => {
      try {
        if (loading || noMore) return;
        const scrollTop = window.scrollY || document.documentElement.scrollTop || document.body.scrollTop || 0;
        const viewportH = window.innerHeight || document.documentElement.clientHeight || 0;
        const fullH = document.documentElement.scrollHeight || document.body.scrollHeight || 0;
        if (scrollTop + viewportH >= fullH - 200) {
          fetchPage(page + 1, false);
        }
      } catch { }
    };
    scrollHandlerRef.current = handleScroll;
    window.addEventListener('scroll', handleScroll, { passive: true } as any);
    window.addEventListener('resize', handleScroll, { passive: true } as any);
    return () => {
      try { window.removeEventListener('scroll', handleScroll as any); } catch { }
      try { window.removeEventListener('resize', handleScroll as any); } catch { }
    };
  }, [page, loading, noMore, fetchPage]);

  // 事件：点击列表项 -> 打开弹窗
  const onClickItem = (it: LikedWork) => {
    setCurrent(it);
    setModalOpen(true);
  };

  const toggleSelect = (id: number) => {
    setSelectedIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
  };

  // 事件：确认“移除喜欢” -> 请求接口并从列表移除
  const onConfirmUnlike = async (workId: number) => {
    try {
      const authHeader = getStoredBearerToken();
      if (!authHeader) return;
      // 语言码（示例使用大写以兼容服务端大小写敏感）
      const langUpper = toApiLanguageCode(locale as any).toUpperCase();
      const res = await request.post('/api/work/toggleWorkLikeRoute', { work_id: workId, language: langUpper }, { headers: { Authorization: authHeader } });
      if (res?.data?.success === true) {
        // 从列表移除该项
        setList((prev) => prev.filter((x) => x.id !== workId));
        setModalOpen(false);
        setCurrent(null);
      }
    } catch (e) {
      // 忽略错误，拦截器会统一提示
    }
  };

  // 卡片层面的取消喜欢（单项），使用 batchCancelWorkLikesRoute 接口并携带 language
  const handleConfirmCardUnlike = async (workId: number) => {
    try {
      setConfirmLoadingCard(true);
      const authHeader = getStoredBearerToken();
      if (!authHeader) return;

      // 映射当前 locale 到接口期望的 language 码
      const mapLocaleToApiLang = (loc: string | undefined) => {
        const m: Record<string, string> = {
          en: 'en',
          ja: 'jp',
          es: 'xby',
          fr: 'fy',
          ru: 'ey',
        };
        return loc && m[loc] ? m[loc] : toApiLanguageCode(loc as any);
      };

      const lang = mapLocaleToApiLang(locale as any);
      const payload = { work_id: [workId], language: lang };

      const res = await request.post('/api/work/batchCancelWorkLikesRoute', payload, { headers: { Authorization: authHeader } });
      if (res?.data?.success === true) {
        // 从列表移除已取消的 id（若返回 removed 可用于计数）
        setList((prev) => prev.filter((it) => it.id !== workId));
        setTotal((t) => Math.max(0, t - (res.data.removed ?? 1)));
        // 关闭弹窗
        setConfirmOpenCard(false);
        setConfirmTargetId(null);
      }
    } catch (e) {
      // 忽略，拦截器处理提示
    } finally {
      setConfirmLoadingCard(false);
    }
  };

  // 事件：“创建图片” -> 携带 template_id/role_prompt/image_url 跳转，但不在 URL 暴露
  const onCreateImage = (it: LikedWork) => {
    try {
      navigate('/CreateImage', { state: { id: it.template_id, image_url: it.image_url, role_prompt: it.role_prompt, category: (it as any)?.category } });
    } catch { }
  };

  // 渲染：单个卡片（适配移动/PC + 明暗主题）
  const renderCard = (it: LikedWork) => (
    <div
      key={it.id}
      className="relative rounded-xl overflow-hidden border border-gray-200 dark:border-gray-700 bg-white dark:bg-[#0b0b0b] shadow hover:shadow-md transition cursor-pointer"
      onClick={() => onClickItem(it)}
    >
      {editMode && (
        <input
          type="checkbox"
          checked={selectedIds.includes(it.id)}
          onChange={() => toggleSelect(it.id)}
          className="absolute top-2 left-2 z-30 w-5 h-5"
          onClick={(e) => e.stopPropagation()}
        />
      )}
      {/* 图片区域：保持 1024×1712 比例，使用 object-cover 填充 */}
      <div className="relative w-full" style={{ paddingTop: '167.1875%' }}>
        <img
          src={it.image_url}
          alt={t('my_liked_workList.image_alt')}
          className="absolute inset-0 w-full h-full object-cover"
          loading="lazy"
        />
      </div>

      {/* 底部信息区：作者与点赞 */}
      <div className="px-3 py-2 flex items-center justify-between">
        <div className="flex items-center min-w-0">
          <img src={it.avatar_url || ''} alt={it.nickname || ''} className="w-6 h-6 rounded-full object-cover border border-gray-200 dark:border-gray-700" />
          <span className="ml-2 text-sm text-gray-700 dark:text-gray-200 truncate max-w-[8rem] md:max-w-[12rem]">{it.nickname || ''}</span>
        </div>
        {/* 点赞区域（点击时仅触发卡片级二次确认，不触发展示详情） */}
        <div className="flex items-center text-gray-600 dark:text-gray-300 text-sm">
          <button
            onClick={(e) => {
              e.stopPropagation();
              setConfirmTargetId(it.id);
              setConfirmOpenCard(true);
            }}
            className="inline-flex items-center gap-1 px-2 py-1 rounded hover:bg-gray-100 dark:hover:bg-[#111]"
            aria-label={t('my_liked_workList.unlike')}
            disabled={confirmLoadingCard}
          >

            <span className={"w-4 h-4 mr-1 " + (it.likes_count ? 'text-red-500' : 'text-gray-500')}>
              <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2507" width="18" height="18" className="text-inherit"><path d="M512 998.4c-19.2 0-38.4-12.8-38.4-19.2C454.4 966.4 128 640 83.2 595.2 32 537.6 0 467.2 0 396.8s32-147.2 83.2-198.4c51.2-51.2 121.6-83.2 198.4-83.2 76.8 0 147.2 32 198.4 83.2C492.8 211.2 505.6 224 512 236.8c6.4-12.8 19.2-25.6 32-38.4 51.2-51.2 121.6-83.2 198.4-83.2 76.8 0 147.2 32 198.4 83.2C992 249.6 1024 320 1024 396.8c0 76.8-32 147.2-83.2 198.4C896 640 569.6 966.4 550.4 979.2 550.4 985.6 531.2 998.4 512 998.4z" fill="currentColor" p-id="2346"></path></svg>
            </span>
            <span className="text-gray-700 dark:text-gray-200 mt-1">{it.likes_count ?? 0}</span>
          </button>
        </div>
      </div>
    </div>
  );

  // 批量取消喜欢请求
  const handleBulkCancel = async () => {
    if (selectedIds.length === 0) return;
    try {
      setBulkConfirmLoading(true);
      const authHeader = getStoredBearerToken();
      if (!authHeader) return;
      const lang = toApiLanguageCode(locale as any);
      const payload = { work_id: selectedIds, language: lang };
      const res = await request.post('/api/work/batchCancelWorkLikesRoute', payload, { headers: { Authorization: authHeader } });
      if (res?.data?.success) {
        // 从列表中移除已取消的 id（服务器返回可能更复杂，这里以请求成功为准）
        setList((prev) => prev.filter((it) => !selectedIds.includes(it.id)));
        setTotal((t) => Math.max(0, t - (res.data.removed ?? selectedIds.length)));
        setSelectedIds([]);
        setBulkConfirmOpen(false);
        setEditMode(false);
      }
    } catch (e) {
      // 忽略，拦截器会处理提示
    } finally {
      setBulkConfirmLoading(false);
    }
  };

  // 批量取消喜欢确认弹窗渲染
  const renderBulkConfirm = () => {
    if (!bulkConfirmOpen) return null;
    return (
      <div className="fixed inset-0 z-[12000] flex items-center justify-center p-4">
        <div className="absolute inset-0 bg-black/50" onClick={() => bulkConfirmLoading ? null : setBulkConfirmOpen(false)} />
        <div className="relative z-10 w-full max-w-md rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-[#0b0b0b] p-4 shadow-xl">
          <div className="text-base font-semibold text-gray-900 dark:text-gray-100">{t('my_work.bulk_confirm_title')}</div>
          <div className="mt-2 text-sm text-gray-600 dark:text-gray-300">{t('my_work.bulk_confirm_message') + ` (${selectedIds.length})`}</div>
          <div className="mt-4 flex justify-end gap-2">
            <button onClick={() => setBulkConfirmOpen(false)} className="px-3 py-1 rounded text-gray-600 dark:text-gray-300 bg-gray-100" disabled={bulkConfirmLoading}>{t('my_work.cancel')}</button>
            <button onClick={handleBulkCancel} className="px-3 py-1 rounded bg-red-500 text-white" disabled={bulkConfirmLoading}>{bulkConfirmLoading ? t('my_work.please_wait') : t('my_work.confirm')}</button>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="w-full md:w-[70%] mx-auto px-4 md:px-6 md:py-6 min-h-[var(--content-h)] sm:min-h-full">
      {/* 自定义返回标题栏 */}
      <div className="sticky justify-between top-0 z-20 bg-white/80 dark:bg-[#111111]/80 backdrop-blur border-b border-gray-200 dark:border-gray-800 h-14 flex items-center ">
        <button
          onClick={goBack}
          className="rounded flex items-center text-black dark:text-white hover:bg-gray-100 dark:hover:bg-[#1a1a1a]"
          aria-label={t('my_liked_workList.back')}
        >
          <svg viewBox="0 0 24 24" width="22" height="22" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M15 18l-6-6 6-6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
          <h2 className="text-base md:text-lg font-semibold text-gray-900 dark:text-gray-100">{t('my_liked_workList.page_title')}</h2>
        </button>
        <div className="absolute right-3 flex items-center gap-2">
          {editMode && (
            <button
              onClick={() => setBulkConfirmOpen(true)}
              className="px-3 py-1 rounded bg-red-500 text-white text-sm"
            >
              {t('my_work.delete_selected')}
            </button>
          )}
          <button
            onClick={() => {
              setEditMode((v) => !v);
              if (editMode) setSelectedIds([]);
            }}
            className="px-3 py-1  dark:bg-gray-100 bg-[#111] dark:text-black text-sm rounded"
          >
            {editMode ? t('my_work.cancel') : t('my_work.management')}
          </button>
        </div>
      </div>

      {/* 列表（响应式网格）：移动端两列，PC 端 4/6 列 */}
      <div className="grid grid-cols-2 sm:grid-cols-2 mt-4 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 gap-3 md:gap-4">
        {list.map(renderCard)}
      </div>

      {/* 底部加载状态 */}
      <div className="flex items-center justify-center py-4 text-sm text-gray-500 dark:text-gray-400">
        {loading ? t('my_liked_workList.loading') : noMore ? (list.length ? t('my_liked_workList.no_more') : t('my_liked_workList.no_data')) : t('my_liked_workList.scroll_to_load')}
      </div>

      {/* 详情弹窗 */}
      <LikedWorkModal
        open={modalOpen}
        item={current}
        onClose={() => setModalOpen(false)}
        onConfirmUnlike={async (id: number) => onConfirmUnlike(id)}
        onCreateImage={(it: { id: number; template_id?: number; image_url: string; role_prompt?: string }) => onCreateImage(it as any)}
      />
      {/* 卡片层面的移除喜欢二次确认弹窗 */}
      {confirmOpenCard && confirmTargetId !== null && (
        <div className="fixed inset-0 z-[12000] flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-black/50" onClick={() => confirmLoadingCard ? null : setConfirmOpenCard(false)} />
          <div className="relative z-10 w-full max-w-sm rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-[#0b0b0b] p-4 shadow-xl">
            <div className="text-base font-semibold text-gray-900 dark:text-gray-100">{t('my_liked_workList.confirm_title') || t('my_work.confirm_title')}</div>
            <div className="mt-2 text-sm text-gray-600 dark:text-gray-300">{t('my_liked_workList.confirm_message') || t('my_work.confirm_message')}</div>
            <div className="mt-4 flex justify-end gap-2">
              <button
                className="px-3 py-1.5 text-sm text-gray-500 dark:text-gray-400 rounded border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-[#111]"
                onClick={() => setConfirmOpenCard(false)}
                disabled={confirmLoadingCard}
              >
                {t('my_work.cancel')}
              </button>
              <button
                className="px-3 py-1.5 text-sm rounded bg-red-600 text-white hover:opacity-90"
                onClick={async () => {
                  try {
                    await handleConfirmCardUnlike(confirmTargetId as number);
                  } finally {
                    // handled in function
                  }
                }}
                disabled={confirmLoadingCard}
              >
                {confirmLoadingCard ? t('my_work.please_wait') : t('my_work.confirm')}
              </button>
            </div>
          </div>
        </div>
      )}
      {renderBulkConfirm()}
    </div>
  );
};

export default MyLikedWorkListPage;


